package com.example.fragment;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.adapter.MyAdapterTest;
import com.example.android.ArticleTest;
import com.example.android.MyThreadTest;
import com.example.androidtest.MyAdapter;
import com.example.androidtest.R;
import com.example.androidtest.R.layout;

import android.R.raw;
import android.content.Context;
import android.database.CursorJoiner.Result;
import android.R.raw;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;

public class Person_Fragment extends Fragment {
	private ViewPager vp_person;
	private MyAdapterTest adapter;
	private Handler handler;
	private ArrayList<ArticleTest> list;
	private String result;
	private Context context;
	private String url = "http://www.mengxianyi.net/one/article.json";

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.fragment_person, null);
		vp_person = (ViewPager) view.findViewById(R.id.vp_person1);

		handler = new Handler(new Handler.Callback() {

			@Override
			public boolean handleMessage(Message msg) {
				if (msg.what == 100) {
					result = (String) msg.obj;
					list = getData();
					adapter = new MyAdapterTest(getActivity(), list);
					vp_person.setAdapter(adapter);
				}
				return false;
			}
		});
		new MyThreadTest(handler, url).start();

		return view;
	}

	public ArrayList<ArticleTest> getData() {
		ArrayList<ArticleTest> data = new ArrayList<>();
		try {
			JSONObject object = new JSONObject(result);
			if (object.has("data")) {
				JSONArray array = object.getJSONArray("data");
				for (int i = 0; i < array.length(); i++) {
					ArticleTest articleTest = new ArticleTest();
					JSONObject o = array.getJSONObject(i);
					if (o.has("title")) {
						String title = o.getString("title");
						articleTest.setTitle(title);
					}
					if (o.has("author")) {
						String author = o.getString("author");
						articleTest.setAuthor(author);
					}
					if (o.has("content")) {
						String content = o.getString("content");
						articleTest.setContent(content);
					}
					if (o.has("date")) {
						String date = o.getString("date");
						articleTest.setDate(date);
					}
					if (o.has("image")) {
						String image = o.getString("image");
						articleTest.setImage(image);
					}
					data.add(articleTest);

				}
			}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return data;
	}

}
